programming4us
           
 
 
Programming

jQuery 1.3 : Improving a basic form (part 7)

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
12/6/2010 5:51:12 PM
Required formats

There is one further type of validation to implement in our contact form—correct input formats. Sometimes it can be helpful to provide a warning if text is entered into a field incorrectly (rather than simply having it blank). Prime candidates for this type of warning are email, phone, and credit-card fields. For our demonstration, we will put in place a relatively simple regular-expression test for the email field. Let's take a look at the full code for the email validation before we dig into the regular expression in particular:

$(document).ready(function() {
// . . . code continues . . .
if (this.id == 'email') {
var $listItem = $(this).parents('li:first');
if ($(this).is(':hidden')) {
this.value = '';
}
if (this.value != '' &&
!/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)) {
var errorMessage = 'Please use proper e-mail format'
+ ' (e.g. [email protected])';
$('<span></span>')
.addClass('error-message')
.text(errorMessage)
.appendTo($listItem);
$listItem.addClass('warning');
}
}
// . . . code continues . . .
});

The code performs the following tasks:

  • Tests for the id of the email field; if the test is successful:

    • Sets a variable for the parent list item.

    • Tests for the hidden state of the email field. If it is hidden (which happens when its corresponding checkbox is unchecked), its value is set to an empty string. This allows our previous warning class and error message removal to work properly for email fields as well.

    • Tests that the field value is not an empty string and that the field value does not match the regular expression. If the two tests are successful, the script:

  • Creates an error message

  • Inserts the message in<span class="error-message">

  • Appends the<span class="error-message"> element and its contents to the parent list item

  • Adds the warning class to the parent list item

Now let's take a look at the regular expression in isolation:

!/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)

Although this regular expression is similar to the one we created earlier in the chapter, it uses the .test() method rather than the .replace() method, since we only need it to return true or false. As before, the regular expression goes between the two forward slashes. It is then tested against a string that is placed inside the parentheses of, in this case the value of the email field. .test()

In this regular expression, we look for a group of one or more non-linefeed characters (.+), followed by an @ symbol, and then followed by another group of one or more non-linefeed characters. So far, a string such as lucia@example would pass the test, as would millions of other permutations, even though it is not a valid email address.

We can make the test more precise by looking for a. character, followed by two through four letters between a and z at the end of the string. That is exactly what the remaining portion of the regular expression does. It first looks for a character between a and z or A and Z&mdash;[a-zA-Z]. It then says that a letter in that range can appear two through four times only&mdash;{2,4}. Finally, it insists that those two through four letters appear at the end of the string: $. Now a string such as [email protected] would return true, whereas lucia@example&mdash;or [email protected] or [email protected] or lucia-example.com&mdash;would return false.

But we want true returned (and the error message, etc., created) only if the proper email address format is not entered. That's why we precede the test expression with the exclamation mark (not operator):

!/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)

A final check

The validation code is now almost complete for the contact form. We can validate the form's fields one more time when the user attempts to submit it, this time all at once. Using the .submit() event handler on the form (not the Send button) we trigger blur on all of the required fields:

$(document).ready(function() {
$('form').submit(function() {
$('#submit-message').remove();
$(':input.required').trigger('blur');
});
});

Note here that we've sneaked in a line to remove an element that does not yet exist:<div id="submit-message">. We'll add this element in the next step. We're just preemptively removing it here because we already know that we'll need to do it based on the problems we encountered with creating multiple error messages earlier in the chapter.

After triggering blur, we get the total number of warning classes in the current form. If there are any at all, we'll create a new<div id="submit-message"> and insert it before the Send button where the user is most likely to see it. We also stop the form from actually being submitted:

$(document).ready(function() {
$('form').submit(function() {
$('#submit-message').remove();
$(':input.required').trigger('blur');
var numWarnings = $('.warning', this).length;
if (numWarnings) {
$('<div></div>')
.attr({
'id': 'submit-message',
'class': 'warning'
})
.append('Please correct errors with ' +
numWarnings + ' fields')
.insertBefore('#send');
return false;
}

});
});


In addition to providing a generic request to fix errors, the message indicates the number of fields that need to be fixed:

We can do better than that, however; rather than just showing the number of errors, we can list the names of the fields that contain errors:

$(document).ready(function() {
$('form').submit(function() {
$('#submit-message').remove();
$(':input.required').trigger('blur');
var numWarnings = $('.warning', this).length;
if (numWarnings) {
var list = [];
$('.warning label').each(function() {
list.push($(this).text());
});

$('<div></div>')
.attr({
'id': 'submit-message',
'class': 'warning'
})
.append('Please correct errors with the following ' +
numWarnings + ' fields:<br />')
.append('&bull; ' + list.join('<br />&bull; '))

.insertBefore('#send');
return false;
};
});
});



The first change to the code is the list variable set to an empty array. Then, we get each label that is a descendant of an element with the warning class and push its text into the list array (with the native JavaScript push function). Now, the text of each of these labels constitutes a separate element in the list array.

We modify our first version of the<div id="submit-message"> content a bit and append our list array to it. Using the native JavaScript join() function to convert the array into a string, we join each of the array's elements with a line break and a bullet:

Admittedly, the HTML for the field list is presentational rather than semantic. However, for an ephemeral list&mdash;one that is generated by JavaScript as a last step and meant to be discarded as soon as possible&mdash;we'll forgive this quick and dirty code for the sake of ease and brevity.

Other -----------------
- Changes to Privacy Risk Management and Compliance in Relation to Cloud Computing
- Cloud Security and Privacy : What Are the Key Privacy Concerns in the Cloud?
- Cloud Security and Privacy : What Is the Data Life Cycle?
- Making Your Site Accessible to Search Engines
- Security Management in the Cloud - Security Vulnerability, Patch, and Configuration Management (part 2)
- Security Management in the Cloud - Security Vulnerability, Patch, and Configuration Management (part 1)
- Security Management in the Cloud - Access Control
- Security Management in the Cloud - IaaS Availability Management
- Security Management in the Cloud - PaaS Availability Management
- Security Management in the Cloud - SaaS Availability Management
- Security Management in the Cloud - Availability Management
- Security Management in the Cloud
- The Art of SEO : Trending, Seasonality, and Seasonal Fluctuations in Keyword Demand
- The Art of SEO : Leveraging the Long Tail of Keyword Demand
- The Art of SEO : Determining Keyword Value/Potential ROI
- Identity and Access Management : Cloud Service Provider IAM Practice
- Identity and Access Management : Cloud Authorization Management
- Identity and Access Management : IAM Practices in the Cloud (part 2) - Federated Identity
- Identity and Access Management : IAM Practices in the Cloud (part 1) - Cloud Identity Administration
- iPad SDK : Keyboard Extensions and Replacements (part 4) - Creating the Calculator
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us